using System;
using Pumpkin.Utils;

namespace Pumpkin.FrameBase
{
    public class CrossDomainInstance
    {
        public object Instance { get { return instance_; } }
        public CrossDomainInfo CrossInfo { get { return info_; } }

        private object instance_;
        private CrossDomainInfo info_;

        public CrossDomainInstance(CrossDomainInfo objInfo)
        {
            info_ = objInfo;
        }

        public void SetInstance(object instance)
        {
            instance_ = instance;
        }

        public void CreateCrossInstance(params object[] args)
        {
            if (instance_ != null)
            {
                Log.LogError("An instance of " + info_.ClassName + " has already instantiated !!");
                return;
            }

            instance_ = ILRTUtils.GetDomain().Instantiate(CrossInfo.ClassName, args);
            if (instance_ == null)
            {
                string error = string.Format("cant instantial class {0}", CrossInfo.ClassName);
                throw new InvalidOperationException(error);
            }
        }

        public void CreateCrossInstance()
        {
            if (instance_ != null)
            {
                Log.LogError("An instance of " + info_.ClassName + " has already instantiated !!");
                return;
            }

            instance_ = ILRTUtils.GetDomain().Instantiate(CrossInfo.ClassName);
            if (instance_ == null)
            {
                string error = string.Format("cant instantial class {0}", CrossInfo.ClassName);
                throw new InvalidOperationException(error);
            }
        }
    }

    public class CrossInstanceFactory : Singleton<CrossInstanceFactory>
    {
        public CrossDomainInstance Create(string clsName)
        {
            var info = CrossDomainInfoFactory.Instance.Create(clsName);
            return new CrossDomainInstance(info);
        }

        public CrossDomainInstance CreateWithInstantial(string clsName)
        {
            var instance = Create(clsName);
            instance.CreateCrossInstance();
            return instance;
        }

        public CrossDomainInstance CreateWithInstantial(string clsName, params object[] args)
        {
            var instance = Create(clsName);
            instance.CreateCrossInstance(args);
            return instance;
        }
    }

}